关于缓存实例(cached instance),可以参考Python中的弱引用
利用Python中的元类实现缓存实例(cached instance)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import weakref
class Cached(type):
def __init__(self, *args, **kwargs):
super(Cached, self).__init__(*args, **kwargs)
# 建立一个value为弱引用的对象
self.__cache = weakref.WeakValueDictionary()
def __call__(self, *args):
if args in self.__cache:
return self.__cache[args]
else:
# 注意,这里的self为Spam.Spam已经通过元类创建了__cache对象
obj = super(Cached, self).__call__(*args)
self.__cache[args] = obj
return obj
class Spam(metaclass=Cached):
def __init__(self, name):
print('Creating Spam({!r})'.format(name))
self.name = name
if __name__ == '__main__':
a = Spam('foo')
b = Spam('bar')
print('a is b:', a is b)
c = Spam('foo')
print('a is c:', a is c)
本文标题:利用Python中的元类实现缓存实例(cached instance)
文章作者:Vincent Zhong
发布时间:2016-09-27, 12:37:41
最后更新:2019-07-07, 13:13:09
原始链接:https://wax8280.github.io/2016/09/27/利用Python中的元类实现缓存实例(cached instance)/
许可协议: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。